import { nanoid } from '@reduxjs/toolkit'
import { Typography } from 'antd'
import React, { useCallback } from 'react'
import { useDispatch } from 'react-redux'
import { componentConfGroup, ComponentConfType } from '../../../components/QuestionComponents/index'
import { addComponent } from '../../../store/componentsReducer'

import styles from './ComponentLib.module.scss'

function genComponent({ title, type, Component, defaultProps }: ComponentConfType) {
  const dispatch = useDispatch()

  const handleClick = useCallback(function handleClick() {
    const newComponent = {
      fe_id: nanoid(),
      title,
      type,
      props: defaultProps,
    }

    dispatch(addComponent(newComponent))
  }, [])

  /* function handleClick() {
    const newComponent = {
      fe_id: nanoid(),
      title,
      type,
      props: defaultProps,
    }

    dispatch(addComponent(newComponent))
  } */

  return (
    <div key={type} className={styles.wrapper} onClick={() => handleClick()}>
      <div className={styles.component}>
        <Component />
      </div>
    </div>
  )
}
const ComponentLib: React.FC = () => {
  return (
    <>
      {componentConfGroup.map(({ groupName, components }, index) => {
        return (
          <div key={index}>
            <Typography.Title
              level={3}
              style={{ fontSize: '16px', marginTop: index > 0 ? '20px' : 0 }}
            >
              {groupName}
            </Typography.Title>
            <div>{components.map(c => genComponent(c))}</div>
          </div>
        )
      })}
    </>
  )
}

export default ComponentLib
